import { defineStore } from 'pinia';
import request from '@/utils/request';
import router from '@/router';
import { showNotification } from '@/utils/notify';
import {jwtDecode} from 'jwt-decode';

export const useUserStore = defineStore('user', {
    // 定义状态
    state: () => ({
        isLoggedIn: false,
        username: '',
        role:'',
        token:''
    }),
    // 定义修改状态的方法
    actions: {
        SET_TOKEN(token: string) {
            this.token = token
            localStorage.setItem('token', token)
        },
     
        setIsLoggedIn(status: boolean) {
            this.isLoggedIn = status;
        },
        setUsername(name: string) {
            this.username = name;
        },

        async logIn(loginForm: { userType: string; userId: string; password: string; }) {
            try {
                // 将用户类型也传递到后端
                const { data } = await request.post<{ code: number, data: { token: string } }>('/api/login', {
                 ...loginForm,
                  userType: loginForm.userType
                });
                
                this.isLoggedIn = true;
                const loginInfo = jwtDecode(data.token) as { username: string, role: string };
                this.username = loginInfo.username;
                this.role = loginInfo.role;
                this.SET_TOKEN(data.token)
                showNotification('登录成功');
              } catch (error) {
                showNotification("登录失败", true);
              }
        },

        logOut(){
            this.username = ''
            this.token = ''
            localStorage.clear()
            this.isLoggedIn = false
        }
    },
    // 定义获取状态的计算属性
    getters: {
        getIsLoggedIn: (state) => state.isLoggedIn
       

    },
    persist: {
      key: 'user-store', // 存储在 localStorage 或 sessionStorage 中的键名
      storage: localStorage, // 存储方式，也可以使用 sessionStorage
    },
});